﻿namespace CodeSHARPer.ViewModel
{
    using CodeSHARPer.Services;
    using CodeSHARPer.ViewModel.Base;
    using CodeSHARPer.ViewModel.Dialogs;
    using System;
    using System.IO;

    internal partial class Workspace : ViewModelBase
    {
        private ConfigViewModel config = null;

        /// <summary>
        /// Get/set program settings for entire application
        /// </summary>
        public ConfigViewModel Config
        {
            get
            {
                if (config == null)
                    config = new ConfigViewModel();

                return config;
            }
            internal set
            {
                if (config != value)
                {
                    config = value;
                    NotifyPropertyChanged(ObservableHelper.CreateArgs<Workspace>(x => x.Config));
                }
            }
        }

        /// <summary>
        /// Save application settings when the application is being closed down
        /// </summary>
        public void SaveConfigOnAppClosed()
        {
            try
            {
                App.CreateAppDataFolder();

                this.Config.LastOpenedFiles = this.RecentFiles.OpenedFilesManager;

                // Save/initialize program options that determine global program behaviour
                ConfigViewModel.SaveOptions(App.DirFileAppSessionData, this.Config);
            }
            catch (Exception exp)
            {
                ServiceResolver.Instance.MessageBoxService.ShowError(exp.ToString(), "Unhandled Exception");
            }
        }

        /// <summary>
        /// Load configuration from persistence on startup of application
        /// </summary>
        public void LoadConfigOnAppStartup()
        {
            ConfigViewModel retOpts = null;

            try
            {
                // Re/Load program options to control global behaviour of program
                if ((retOpts = ConfigViewModel.LoadOptions(App.DirFileAppSessionData)) == null)
                    retOpts = new ConfigViewModel();
            }
            catch { }
            finally
            {
                if (retOpts == null)
                    retOpts = new ConfigViewModel();
            }

            this.Config = retOpts;

            this.IsToolBarVisible = this.Config.IsToolBarVisible;
        }
    }
}
